package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    //发布动态
    @Override
    public void publish(Movement movement) {
        try {
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            //保存动态详情
            mongoTemplate.save(movement);
            /*//查询当前用户的好友数据
            Query query = Query.query(Criteria.where("userId").is(movement.getUserId()));
            List<Friend> friends = mongoTemplate.find(query, Friend.class);
            //循环好友数据，构建时间线数据存入数据库
            for (Friend friend : friends) {
                MovementTimeLine mtl = new MovementTimeLine();
                mtl.setMovementId(movement.getId());
                mtl.setUserId(friend.getUserId());
                mtl.setFriendId(friend.getFriendId());
                mtl.setCreated(System.currentTimeMillis());
                mongoTemplate.save(mtl);
            }*/
            timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    //分页动态查询
    @Override
    public PageResult findByUserId(Long userId, int page, int pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0,movements);
    }

    //查询当前用户好友发布的所有动态
    @Override
    public List<Movement> findFriendMovements(Long friendId, Integer page, Integer pagesize) {
        //根据friendId查询时间线表
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> list = mongoTemplate.find(query, MovementTimeLine.class);
        //提取动态id列表
        List<ObjectId> movementIds = CollUtil.getFieldValues(list, "movementId",ObjectId.class);
        //根据动态id查询动态查询
        Query query1 = Query.query(Criteria.where("id").in(movementIds));
        return mongoTemplate.find(query1,Movement.class);
    }

    //随机获取
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //创建统计对象,设置统计参数
       TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(counts));
        //调用mongoTemplate的方法进行统计
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(aggregation, Movement.class);
        //获取统计结果
        return aggregate.getMappedResults();
    }

    //根据PID查询
    @Override
    public List<Movement> findByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query,Movement.class);
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }

}
